import 'dart:math';

import 'package:flutter/material.dart';

import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:junyeyishu/widgets/QGListState.dart';

@immutable
class QGMineNFTListWidget extends StatefulWidget {
  dynamic data;

  QGMineNFTListWidget({super.key, this.data});
  @override
  State<QGMineNFTListWidget> createState() => _QGMineNFTListWidgetState();

  static show(context, data) {
    showDialog(
        useSafeArea: false,
        context: context,
        builder: (context) {
          return QGMineNFTListWidget(data: data);
        });
  }
}

class _QGMineNFTListWidgetState extends QGListState<QGMineNFTListWidget> {
  @override
  void initState() {
    super.initState();

    listURL = url_user_getMyNftListByGoods;
    listKey = "list";

    gridDelegate = SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: 3,
      mainAxisSpacing: 10.rpx,
      crossAxisSpacing: 10.rpx,
      childAspectRatio: 105 / 80,
    );

    onRefresh();
  }

  @override
  Map listParam() {
    return {"pid": widget.data?["pid"], "limit": 20};
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Stack(
          clipBehavior: Clip.none,
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10.rpx),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.rpx),
                color: Color(0xFF232A32),
              ),
              child: Column(
                children: [
                  buildHeader(),
                  SizedBox(height: 30.rpx),
                  buildListContainer(),
                  SizedBox(height: max(10.rpx, kSafeBottom)),
                ],
              ),
            ),
            buildClose(),
            Positioned(
                top: 20.rpx,
                left: 20.rpx,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10.rpx),
                  child: QGImage(
                      url: widget.data?["thumb_img"],
                      width: 105.rpx,
                      height: 105.rpx),
                ))
          ],
        ),
      ],
    );
  }

  buildClose() {
    return Positioned(
      right:10.rpx,
      child: GestureDetector(
        onTap: onClose,
        child: Container(
          padding: EdgeInsets.all(12.rpx),
          child: QGImage(asset: "shade_close",width: 15.rpx,),
        ),
      ),
    );
  }

  buildHeader() {
    var name = widget.data?["name"];
    if (name is! String || name.isEmpty) {
      name = " ";
    }

    return Row(
      children: [
        SizedBox(width: 125.rpx),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 60.rpx),
              FittedBox(
                child: Text(
                  name,
                  style: TextStyle(
                      color: Color(0xFFFFFFFF),
                      fontSize: 16.rpx,
                      fontWeight: FontWeight.bold),
                ),
              ),
              SizedBox(height: 6.rpx),

              Text(
                '(共${widget.data?["goods_num"]}份)',
                style: TextStyle(
                    color: Color(0XFF989EA4),
                    fontSize: 14.rpx,
                    fontWeight: FontWeight.normal),
              ),
            ],
          ),
        ),
        SizedBox(width: 10.rpx),
      ],
    );
  }

  getListHeight(int count) {
    count = max(1, count);

    int lines = count ~/ 3;
    if (count % 3 > 0) {
      lines += 1;
    }
    var itemH = (kScreenWidth - (20.rpx)) / 3 / (105 / 80);

    var perCount = 4;
    if (perCount * itemH > kScreenHeight * 0.8) {
      perCount -= 1;
    }

    return min(lines, perCount) * itemH;
  }

  buildListContainer() {
    var count = 1;
    if (list != null) {
      if (list.length == 0) {
        count = 9;
      } else {
        count = list.length;
      }
    }

    return SizedBox(
        height: getListHeight(count),
        child: Column(
          children: [
            buildList(),
          ],
        ));
  }

  @override
  itemBuilder(ctx, index, data) {
    return GestureDetector(
        onTap: () {
          toDetail(data);
        },
        child: buildCell(data));
  }

  buildCell(data) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(6.rpx),
      child: Stack(
        children: [
          AspectRatio(
            aspectRatio: 105 / 80,
            child: QGImage(url: widget.data?["thumb_img1"]),
          ),
          AspectRatio(
            aspectRatio: 105 / 80,
            child: Container(color:Color(0XFF0C1012)),
          ),
          Align(
            alignment: Alignment.center,
            child: Text(
              '￥${inReview() ? "888" : data?["curPrice"]}',
              style: TextStyle(
                  color: const Color(0xffffffff),
                  fontSize: 16.rpx,
                  fontWeight: FontWeight.bold),
            ),
          ),
          SizedBox(height: 8.rpx),
          Align(
            alignment: Alignment.bottomCenter,
            child: FittedBox(
              child: Container(
                padding: EdgeInsets.only(bottom: 10.rpx),
                child: Text(
                  '#${data?["nft_no"]}/${data?["total"]}',
                  style: TextStyle(
                      color: const Color(0xffffffff),
                      fontSize: 12.rpx,
                      fontWeight: FontWeight.bold),
                ),
              ),
            ),
          ),
          Align(
            alignment: Alignment.topCenter,
            child: Container(
              decoration: BoxDecoration(
                  borderRadius:
                      BorderRadius.only(bottomLeft: Radius.circular(5.rpx),
                      bottomRight: Radius.circular(5.rpx)
                      ),
                  // color: const Color.fromRGBO(7, 193, 96, 0.8),
                  color: data?["isFreeze"] == "0"
                      ? Color(0XFF4AE3FF)
                      : Color(0XFF4AE3FF)),
              padding: EdgeInsets.symmetric(horizontal: 7.rpx, vertical: 5.rpx),
              child: Text(
                data?["isFreeze"] == "0" ? '持有' : '寄售',
                style: TextStyle(
                    color: const Color(0xff111111),
                    fontSize: 10.rpx,
                    fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ],
      ),
    );
  }

  onClose() {
    Navigator.of(context).pop();
  }

  toDetail(data) {
    Navigator.of(context)
        .pushReplacementNamed(
            inReview() ? PageMyReviewNFTDetail : PageMyNFTDetail,
            // inReview() ? PageMyReviewNFTDetail : PageMyReviewNFTDetail,
            arguments: data["nft_id"])
        .then((value) {
      eventBus.fire(EventRefreshMyNFT());
    });
  }
}
